package cn.com.jrr.core.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.jrr.core.common.ToolUtils;
import cn.com.jrr.core.model.DataTableRequest;
import cn.com.jrr.core.model.DataTableResponse;
import cn.com.jrr.core.model.ResponseMessage;
import cn.com.jrr.core.model.power.SysResource;
import cn.com.jrr.core.model.power.SysRole;
import cn.com.jrr.core.model.power.SysRoleResource;
import cn.com.jrr.core.model.power.SysUser;
import cn.com.jrr.core.model.power.SysUserRole;
import cn.com.jrr.core.model.power.TreeNode;
import cn.com.jrr.core.service.power.SysResourceService;
import cn.com.jrr.core.service.power.SysRoleResourceService;
import cn.com.jrr.core.service.power.SysRoleService;


@Controller
@RequestMapping("/power")
public class SysPowerController {
    @Autowired
    private SysResourceService sysResourceService;
    @Autowired
    private SysRoleService sysRoleService;
    private DataTableResponse<SysRole> dt;
    @Autowired
    private ResponseMessage responseMessage;
    private SysRole sysRole;
    @Autowired
    private SysRoleResourceService sysRoleResourceService;


    @RequestMapping("/power")
    public String power(){
        return "/power/role";
    }
    @RequestMapping("/resouse")
    public String powerresouse(){
        return "/power/power";
    }

    @ResponseBody
    @RequestMapping("/list")
    public List<TreeNode> resourceList(Integer id,Integer roleId){
        if(id==null){
            id=1;
        }
        boolean hasChild=true;
        //获取根节点
        SysResource sysResource=sysResourceService.get(id);
        System.out.println(sysResource);

        TreeNode treeNode=new TreeNode();
        treeNode.setId(sysResource.getResourceId());
        treeNode.setText(sysResource.getResourceName());
        hasChild=sysResourceService.hasChildren(sysResource.getResourceId());
        treeNode.setState("close");
        if(!hasChild){
            //控制是否选中
            int belongRole=sysRoleResourceService.getRoleResc(sysResource.getResourceId(),roleId).size();
            if(belongRole>0){
                treeNode.setChecked(true);
            }else{
                treeNode.setChecked(false);
            }
        }
        List<TreeNode> children=new ArrayList<>();
        List<TreeNode> treeNodes=new ArrayList<>();
        treeNode.setChildren(children);
        treeNode.setChildren(getTreeNode(treeNode.getId(),roleId));
        treeNodes.add(treeNode);
        return treeNodes;
    }
    //递归获取子节点
    public List<TreeNode> getTreeNode(Integer id,Integer roleId){
        TreeNode nodeChild=null;
        boolean hasChild=true;
        int belongRole;
        List<TreeNode> nodeChildList=new ArrayList<>();
        List<SysResource> sysResources=sysResourceService.getResource(id);
        if(sysResources.size()>0){
            for(SysResource sr:sysResources){
                nodeChild=new TreeNode();
                nodeChild.setId(sr.getResourceId());
                nodeChild.setText(sr.getResourceName());
                nodeChild.setState("close");
                hasChild=sysResourceService.hasChildren(sr.getResourceId());
                if(hasChild){
                    nodeChild.setChildren(getTreeNode(sr.getResourceId(),roleId));;
                }else{
                    //控制是否选中
                    belongRole=sysRoleResourceService.getRoleResc(sr.getResourceId(),roleId).size();
                    if(belongRole>0){
                        nodeChild.setChecked(true);
                    }else{
                        nodeChild.setChecked(false);
                    }
                }
                nodeChildList.add(nodeChild);
            }

        }
        return nodeChildList;
    }




    @ResponseBody
    @RequestMapping("/roleList")
    public DataTableResponse<SysRole> slist(DataTableRequest dataTableRequest){
        dt=sysRoleService.list(dataTableRequest);
        return dt;
    }


    /**
     * 添加角色信息
     */
    @ResponseBody
    @RequestMapping("/saveaddupdaterole")
    @Transactional
    public ResponseMessage roleAdd(SysRole sysRole){
        try{
            if(sysRole.getRoleId()==null){
                sysRoleService.add(sysRole);
            }else{
                sysRoleService.update(sysRole);
            }
            responseMessage.setStatus("success");
        }catch(Exception e){
            responseMessage.setStatus("fail");
        }
        return responseMessage;
    }

    /**
     * 获取单个角色
     */
    @ResponseBody
    @RequestMapping("/getrole")
    public SysRole roleGet(@RequestParam Integer id){
        sysRole=sysRoleService.get(id);
        return sysRole;
    }
    /**
     * 删除角色
     */
    @ResponseBody
    @RequestMapping("/deleterole")
    public ResponseMessage roleDelete(@RequestParam String idString){
        List<Integer> idList=ToolUtils.splitIdString(idString);
        for(Integer id:idList){
            sysRoleService.delete(id);
        }
        responseMessage.setStatus("success");
        return responseMessage;
    }
    /**
     * @param idString
     * @return
     * ResponseMessage
     *
     */
    @ResponseBody
    @RequestMapping("/assignrole")
    @Transactional
    public ResponseMessage assignRole(SysUserRole sysUserRole){
        try{
            sysRoleService.saveUserRole(sysUserRole);
            responseMessage.setStatus("success");
        }catch(Exception e){
            responseMessage.setStatus("fail");
        }

        return responseMessage;
    }


    @ResponseBody
    @RequestMapping("/roleListByUserId")
    public DataTableResponse<SysRole> userlist(DataTableRequest dataTableRequest,Integer userId){
        dt=sysRoleService.getRoleByUserId(dataTableRequest,userId);
        return dt;
    }


    /**
     * 编辑权限信息
     */
    @ResponseBody
    @RequestMapping("/saveaddupdateresource")
    @Transactional
    public ResponseMessage resouseAdd(SysResource sysResource){
        try{
            if(sysResource.getResourceId()==null){
                if(sysResourceService.getResource(sysResource.getPermit()).size()>0){
                    responseMessage.setStatus("fail");
                    responseMessage.setMessage("该资源已存在");
                }else{
                    sysResourceService.add(sysResource);
                    responseMessage.setStatus("success");
                }

            }else{
                sysResourceService.update(sysResource);
                responseMessage.setStatus("success");
            }

        }catch(Exception e){
            responseMessage.setStatus("fail");
        }
        return responseMessage;
    }
    /**
     * 删除权限信息
     */
    @ResponseBody
    @RequestMapping("/deleteresource")
    @Transactional
    public ResponseMessage resouseDelete(Integer id){
        try{
            sysResourceService.delete(id);
            responseMessage.setStatus("success");
        }catch(Exception e){
            //		responseMessage.setStatus("fail");
        }

        return responseMessage;
    }

    @ResponseBody
    @RequestMapping("/getresource")
    public SysResource resouseGet(Integer id){
        return sysResourceService.get(id);
    }
    @ResponseBody
    @RequestMapping("/saveroleresource")
    @Transactional
    public ResponseMessage saveRoleResource(Integer roleId,String resourceIdStr){
        try{
            String [] resourceIdArry=resourceIdStr.split(",");
            if(resourceIdArry.length>0){
                sysRoleResourceService.delete(roleId);
                for(int i=0;i<resourceIdArry.length;i++){
                    SysRoleResource srr=new SysRoleResource();
                    srr.setResourceId(Integer.parseInt(resourceIdArry[i]));
                    srr.setRoleId(roleId);
                    sysRoleResourceService.saveRoleResource(srr);
                }
                responseMessage.setStatus("success");
            }
        }catch(Exception e){
            responseMessage.setStatus("fail");
        }
        return responseMessage;
    }


}
